<template>
  <div class="invoice-detail-container">
    <page-header title="账单详情" />
    
    <el-card class="invoice-card">
      <template #header>
        <div class="card-header">
          <span>账单信息</span>
          <el-button type="primary" size="small" @click="goBack">返回列表</el-button>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <div v-else-if="invoice" class="invoice-info">
        <el-descriptions border direction="vertical" :column="2">
          <el-descriptions-item label="账单编号">{{ invoice.invoiceId }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ clientName }}</el-descriptions-item>
          <el-descriptions-item label="账单周期">{{ formatDate(invoice.startDate) }} 至 {{ formatDate(invoice.endDate) }}</el-descriptions-item>
          <el-descriptions-item label="总金额">¥{{ invoice.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="开票状态">
            <el-tag :type="getStatusType(invoice.status)">{{ invoice.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="截止日期">{{ formatDate(invoice.dueDate) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(invoice.invoiceDate) }}</el-descriptions-item>
        </el-descriptions>
        
        <h3 class="section-title">费用明细</h3>
        <el-table :data="feeDetails" stripe style="width: 100%">
          <el-table-column prop="feeId" label="费用编号" width="120" />
          <el-table-column prop="recordId" label="记录ID" width="120" />
          <el-table-column prop="calculationDate" label="计费日期" width="150">
            <template #default="scope">
              {{ formatDate(scope.row.calculationDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="daysCounted" label="计费天数" width="100" />
          <el-table-column prop="dailyRate" label="日费率" width="120">
            <template #default="scope">¥{{ scope.row.dailyRate }}</template>
          </el-table-column>
          <el-table-column prop="feeAmount" label="费用金额" width="120">
            <template #default="scope">¥{{ scope.row.feeAmount }}</template>
          </el-table-column>
          <el-table-column prop="ruleId" label="费率规则" />
        </el-table>
      </div>
      
      <div v-else class="not-found">
        <el-empty description="未找到账单信息" />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'InvoiceDetail',
  
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    const invoiceId = route.params.id
    
    const invoice = ref(null)
    const feeDetails = ref([])
    const loading = ref(true)
    
    const clients = computed(() => store.getters.clients || [])
    
    const clientName = computed(() => {
      if (!invoice.value || !clients.value.length) return '未知客户';
      
      const client = clients.value.find(c => c.clientId === invoice.value.clientId);
      return client ? client.clientName : `客户ID: ${invoice.value.clientId}`;
    })
    
    // 获取账单信息
    const fetchInvoiceDetail = async () => {
      try {
        loading.value = true
        
        console.log('获取发票详情，ID:', invoiceId)
        
        // 确保已加载客户列表
        if (clients.value.length === 0) {
          await store.dispatch('fetchClients')
        }
        
        try {
          // 直接使用axios获取发票详情
          const detailUrl = `invoices/${invoiceId}`
          console.log('获取发票详情，URL:', detailUrl)
          const detailResponse = await axios.get(detailUrl)
          invoice.value = detailResponse.data.data
          console.log('获取到的发票详情:', invoice.value)
        } catch (error) {
          console.error('获取发票详情失败:', error)
          ElMessage.error('获取发票详情失败')
          invoice.value = null
        }
        
        // 获取关联的费用明细
        if (invoice.value) {
          try {
            const url = `invoices/${invoiceId}/fees`
            console.log('获取费用明细，URL:', url)
            const response = await axios.get(url)
            feeDetails.value = response.data.data || []
            console.log('获取到的费用明细:', feeDetails.value)
          } catch (error) {
            console.error('获取费用明细失败:', error)
            feeDetails.value = []
          }
        }
        
        loading.value = false
      } catch (error) {
        console.error('获取账单详情失败:', error)
        ElMessage.error('获取账单详情失败')
        loading.value = false
      }
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit'
      })
    }
    
    const getStatusType = (status) => {
      const statusMap = {
        '未开票': 'warning',
        '已开票': 'success',
        '已取消': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    const goBack = () => {
      router.back()
    }
    
    onMounted(() => {
      console.log('InvoiceDetail 组件挂载，路由参数:', route.params)
      fetchInvoiceDetail()
    })
    
    return {
      invoice,
      feeDetails,
      loading,
      clientName,
      getStatusType,
      formatDate,
      goBack
    }
  }
}
</script>

<style scoped>
.invoice-detail-container {
  padding: 20px;
}

.invoice-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  padding: 20px;
}

.section-title {
  margin-top: 30px;
  margin-bottom: 15px;
  font-size: 16px;
  color: #606266;
}

.not-found {
  padding: 40px 0;
}
</style>